﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using ContractManager.BLL.Business;
using ContractManager.Lists.Contracts;
using DevExpress.XtraEditors;
using Stimulsoft.Report;
using Stimulsoft.Report.Components;

namespace ContractManager.Reports.Forms
{
    public partial class FrmBusinessReport : XtraFormBase
    {
        #region "Variable"

        private Entity.Forms _form = new Entity.Forms();
        private bool _allowEdit;
        private bool _onlyView;
        private bool _allowDelete;
        public List<DateTime> ListLockDate { get; set; }

        private DateTime FirstYear;
        private DateTime FromDate;
        private DateTime ToDate;

        #endregion
        #region "Form Construction"
        public FrmBusinessReport()
        {
            InitializeComponent();
        }
        #endregion

        #region "Private Method"

        private void CheckPer(int formNo)
        {
            var item = ClsForms.SelectByUserForm(ClsVariable.RoleNo, formNo);
            if (item == null) return;

            _allowEdit = item.AllowEdit;
            _allowDelete = item.AllowDelete;
            _form = ClsForms.SelectByPk(formNo);
            this.ListLockDate = ClsVoucherLock.GetLockByFormNo(formNo);
        }

        private void BlankForm()
        {
            txtFromValue.EditValue = null;
            txtYear.EditValue = ClsVariable.Year;
            txtType.SelectedIndex = 0;
        }

        private void DoPerform()
        {
            string fileName = ReportName;
            string reportName = ClsVariable.GetReportFullPath(fileName);
            
            var report = new Stimulsoft.Report.StiReport();
            report.Load(reportName);

            ClsVariable.CreateWaitDialog(ClsVariable.StrCaption, "Vui lòng đợi...");
            ClsVariable.SetWaitDialogCaption("Đang nạp dữ liệu báo cáo...");

            DataTable dtReport = ClsReports.GetReportBc05(txtYear.Value, txtFromValue.Value, txtType.SelectedIndex + 1, this.StoreProcedureName);
            if (dtReport.Rows.Count > 0)
            {
                FromDate = Convert.ToDateTime(dtReport.Rows[0]["TuNgay"]);
                ToDate = Convert.ToDateTime(dtReport.Rows[0]["DenNgay"]);
                FirstYear = Convert.ToDateTime(dtReport.Rows[0]["DauNam"]);
                
            }
            report.RegData(dtReport);
            report.Compile();
            report.CompiledReport.Click += click;
            ClsVariable.CloseWaitDialog();
            // In thông tin đơn vị, địa chỉ
            string strKyBaoCao = txtType.SelectedIndex == 0
                              ? String.Format("Tuần {0} năm {1}", txtFromValue.Value, txtYear.Value)
                              : (txtType.SelectedIndex == 1
                                     ? String.Format("Tháng {0} năm {1}", txtFromValue.Value, txtYear.Value)
                                     : (txtType.SelectedIndex == 2
                                            ? String.Format("Quý {0} năm {1}", txtFromValue.Value, txtYear.Value)
                                            : String.Format("Năm {0}",txtYear.Value)));
            report["KyBaoCao"] = strKyBaoCao;

            ClsVariable.ApplyReportParam(report, ClsVariable.DtParam);
            report.Show(this.MdiParent);
            
        }

        private void click(object sender, EventArgs e)
        {
            StiComponent comp = sender as StiComponent;
            if (comp == null) return;
            if (comp.BookmarkValue == null) return;
            string maTk = (string)comp.BookmarkValue;
            string[] arrbm = maTk.Split(';');
            string reportName = arrbm[0];
            reportName = ClsVariable.GetReportFullPath(reportName);
            string storeProcedureName = arrbm[1];
            string code = arrbm[2];
            string mbId = "";
            int conId = 0;
            string conTypeId = "";
            string capId = "";
            string catId = "";
            string workId = "";
            int invID = 0;

            if (maTk != null && reportName.Length > 0 && storeProcedureName.Length>0)
            {
                if (code.StartsWith("14")) FromDate = FirstYear.Date;
                var report = new StiReport();
                try
                {
                    report.Load(reportName);
                    ClsVariable.CreateWaitDialog(ClsVariable.StrCaption, "Vui lòng đợi...");
                    ClsVariable.SetWaitDialogCaption("Đang nạp dữ liệu báo cáo...");
                    
                    DataTable dtReport = storeProcedureName.Equals("usp_Report_BC13")
                        ? ClsReports.GetReportBc13(FromDate, ToDate,
                            mbId, conId)
                        : ClsReports.GetReportBc01(FromDate, ToDate,
                            mbId, storeProcedureName, conId, conTypeId, capId, catId, workId, invID);

                    //DataTable dtReport = ClsReports.GetReportBc01(FromDate, ToDate,
                    //                                      mbId, storeProcedureName, conId, conTypeId, capId, catId, workId, invID);
                    report.RegData(dtReport);
                    report.Compile();
                    report.CompiledReport.Click += clickDetail;
                    ClsVariable.CloseWaitDialog();
                    // In thông tin đơn vị, địa chỉ
                    report["KyBaoCao"] = String.Format("Từ ngày {0} đến ngày {1}", FromDate.ToString("dd/MM/yyyy"), ToDate.ToString("dd/MM/yyyy"));
                    ClsVariable.ApplyReportParam(report, ClsVariable.DtParam);
                    report.Render(true);
                    report.Show(this.MdiParent);

                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show("Có lỗi xảy ra trong quá trình lấy dữ liệu báo cáo " + ex.Message, "Thông báo",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ClsVariable.CloseWaitDialog();
                }


                //report.Render(true);
                //report.Show();

            }
        }

        private void clickDetail(object sender, EventArgs e)
        {
            StiComponent comp = sender as StiComponent;
            if (comp != null && comp.BookmarkValue == null) return;
            if (comp != null)
            {
                var ma = (string)comp.BookmarkValue;
                if (ma == null) return;
                string[] arr = ma.Split(';');
                int voucherId = Convert.ToInt32(arr[0]);
                const int sysBillStyleId = 0;
                int formNo = Convert.ToInt32(arr[1]);
                int vcate = Convert.ToInt32(arr[2]);
                _allowDelete = false;
                CheckPer(formNo);
                if (_allowEdit == false) _onlyView = true;
                if (String.IsNullOrEmpty(_form.Form_Class)) return;
                if (_form.Form_Class.Contains("FrmContracts"))
                {
                    var frm = new FrmContractsDetail()
                    {
                        MasterId = voucherId,
                        AsSysBillStyleId = sysBillStyleId,
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = formNo,
                        FormSysBillStyleIdExport = Convert.ToInt32(_form.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = _form.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = _form.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = _form.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = _form.Form_DetailVatGridLayout,

                        VoucherCate = vcate,
                        IsPrintAfterSave = Convert.ToBoolean(_form.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(_form.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(_form.FormIsNotValidate),
                        LstLockDate = ListLockDate,
                        AllowDelete = _allowDelete,

                        OnlyView = _onlyView,

                        Text = String.Format("Thông tin {0}", _form.Form_Name),
                        MdiParent = this.MdiParent,

                        WindowState = FormWindowState.Maximized
                    };
                    frm.Show();
                    frm.Focus();
                }

                if (_form.Form_Class.Contains("FrmRevenues"))
                {
                    var frm = new FrmRevenuesDetail()
                    {
                        MasterId = voucherId,
                        AsSysBillStyleId = sysBillStyleId,
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = formNo,
                        FormSysBillStyleIdExport = Convert.ToInt32(_form.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = _form.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = _form.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = _form.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = _form.Form_DetailVatGridLayout,

                        VoucherCate = vcate,
                        IsPrintAfterSave = Convert.ToBoolean(_form.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(_form.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(_form.FormIsNotValidate),
                        LstLockDate = ListLockDate,
                        AllowDelete = _allowDelete,

                        OnlyView = _onlyView,

                        Text = String.Format("Thông tin {0}", _form.Form_Name),
                        MdiParent = this.MdiParent,

                        WindowState = FormWindowState.Maximized
                    };
                    frm.Show();
                    frm.Focus();
                }

                if (_form.Form_Class.Contains("FrmDocuments"))
                {
                    var frm = new FrmDocumentsDetail()
                    {
                        MasterId = voucherId,
                        AsSysBillStyleId = sysBillStyleId,
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = formNo,
                        FormSysBillStyleIdExport = Convert.ToInt32(_form.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = _form.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = _form.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = _form.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = _form.Form_DetailVatGridLayout,

                        VoucherCate = vcate,
                        IsPrintAfterSave = Convert.ToBoolean(_form.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(_form.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(_form.FormIsNotValidate),
                        LstLockDate = ListLockDate,
                        AllowDelete = _allowDelete,

                        OnlyView = _onlyView,

                        Text = String.Format("Thông tin {0}", _form.Form_Name),
                        MdiParent = this.MdiParent,

                        WindowState = FormWindowState.Maximized
                    };
                    frm.Show();
                    frm.Focus();
                }

                if (_form.Form_Class.Contains("FrmTenderDocuments"))
                {
                    var frm = new FrmTenderDocumentsDetail()
                    {
                        MasterId = voucherId,
                        AsSysBillStyleId = sysBillStyleId,
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = formNo,
                        FormSysBillStyleIdExport = Convert.ToInt32(_form.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = _form.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = _form.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = _form.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = _form.Form_DetailVatGridLayout,

                        VoucherCate = vcate,
                        IsPrintAfterSave = Convert.ToBoolean(_form.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(_form.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(_form.FormIsNotValidate),
                        LstLockDate = ListLockDate,
                        AllowDelete = _allowDelete,

                        OnlyView = _onlyView,

                        Text = String.Format("Thông tin {0}", _form.Form_Name),
                        MdiParent = this.MdiParent,

                        WindowState = FormWindowState.Maximized
                    };
                    frm.Show();
                    frm.Focus();
                }
            }
        }

        #endregion

        #region "Form Event"
        private void FrmBusinessReportLoad(object sender, EventArgs e)
        {
            BlankForm();
        }
        #endregion


        #region "Button Event"
        private void btnOk_Click(object sender, EventArgs e)
        {
            DoPerform();

        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
        #endregion

        #region "Lookup Event"
        private void txtYear_EditValueChanged(object sender, EventArgs e)
        {
            if (txtYear.Value < 1900) return;
            //If week
            switch (txtType.SelectedIndex)
            {
                case 0://Week
                    {
                        txtFromValue.Properties.MinValue = 1;
                        txtFromValue.Properties.MaxValue = ClsDateUtils.WeeksInYear(Convert.ToInt32(txtYear.Value)); 
                    }
                    break;
                case 1://Month
                    txtFromValue.Properties.MinValue = 1;
                    txtFromValue.Properties.MaxValue = 12;
                    break;
                case 2://Year
                    txtFromValue.Properties.MinValue = 1;
                    txtFromValue.Properties.MaxValue = 4;
                    break;
            }
        }

        private void txtType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtYear.Value < 1900) return;
            //If week
            switch (txtType.SelectedIndex)
            {
                case 0://Week
                    {
                        txtFromValue.Properties.MinValue = 1;
                        txtFromValue.Properties.MaxValue = ClsDateUtils.WeeksInYear(Convert.ToInt32(txtYear.Value));
                    }
                    break;
                case 1://Month
                    txtFromValue.Properties.MinValue = 1;
                    txtFromValue.Properties.MaxValue = 12;
                    break;
                case 2://Year
                    txtFromValue.Properties.MinValue = 1;
                    txtFromValue.Properties.MaxValue = 4;
                    break;
            }
        }
        #endregion

        


    }
}
